#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"snake.h"

// 初始化地图
char map[12][13] = {
	"************",
	"*XXXXH     *",
	"*          *",
	"*          *",
	"*          *",
	"*          *",
	"*          *",
	"*          *",
	"*          *",
	"*          *",
	"*          *",
	"************"
};

// 蛇尾到蛇头在地图中的位置
int snakeX[SNAKE_MAX_LENGTH] = { 1,2,3,4,5 };
int snakeY[SNAKE_MAX_LENGTH] = { 1,1,1,1,1 };
int snakeLength = 5; //蛇的长度

// 当地图中的食物数量不超过2时，放置食物
void put_money(int *food_number) {
    // 食物数量多于2时不做操作
	if (*food_number > 2) {

	}
	else {
		int put_food = MAX_FOOD_NUMBER - *food_number;
		srand(time(NULL));
		for (int i = 0; i < put_food; i++) {
			int x, y;
			x = rand() % 12;
			y = rand() % 12;
			while (map[y][x] != BLANK_CELL) {
				x = rand() % 12;
				y = rand() % 12;
			}
			map[y][x] = SNAKE_FOOD;
			(*food_number)++;
		}
	}
}

// 当地图中的障碍物不超过2时，放置障碍物
void put_obstacle(int *obstacle_number) {
	if (*obstacle_number > 2) {

	}
	else {
		int put_obstacle = MAX_OBSTACLE_NUMBER;
		srand(time(NULL));
		for (int i = 0; i < put_obstacle; i++) {
			int x, y;
			x = rand() % 12;
			y = rand() % 12;
			while (map[y][x] != BLANK_CELL) {
				x = rand() % 12;
				y = rand() % 12;
			}
			map[y][x] = OBSTACLE;
			(*obstacle_number)++;
		}
	}
}

// 输出地图
void output(void) {
	for (int i = 0; i < 12; i++) {
		for (int j = 0; j < 12; j++) {
			printf("%c", map[i][j]);
		}
		printf("\n");
	}
}

// 判断游戏是否结束
int gameover(int is_live) {
	if (is_live == 0) {
		return 1;
	}
	else {
		return 0;
	}
}

int main(){
	int dy, dx; // 移动的方向
	char ch; // 输入字符 W,A,S,D 表示移动的方向
	int is_live = 1; // 蛇的状态：1为活，0为死
	int food_number = 0; // 食物的数量
	int obstacle_number = 0; // 障碍物的数量
	printf("put the food and obstacle:\n");
	put_money(&food_number); 
	put_obstacle(&obstacle_number);
	output();
	int headX, headY;
	printf("please input the first step: ");
	scanf_s(" %c", &ch);
	while (ch != '0') {
		switch (ch) {
		case 'A':
			dy = 0, dx = -1; 
			break;
		case 'D':
			dy = 0, dx = 1;
			break;
		case 'W':
			dy = -1, dx = 0;
			break;
		case 'S':
			dy = 1, dx = 0;
			break;
		}
		headX = snakeX[snakeLength - 1];
		headY = snakeY[snakeLength - 1];
        // 判断移动的方向是否合法
		if (headX + dx == snakeX[snakeLength - 2] && headY + dy == snakeY[snakeLength - 2]) {
			printf("the move is illegal.\n");
			printf("please input the next step: ");
			scanf_s(" %c", &ch);
		}
		else {
			snake_move(dx, dy, &is_live);
			if (gameover(is_live)) {
				printf("game over.\n");
				break;
			}else{
				printf("after moving, the map is: \n");
				output();
				if (food_number < 2) {
					printf("update the map:\n");
					put_money(&food_number);
					put_obstacle(&obstacle_number);
					output();
				}
				printf("please input the next step: ");
				scanf_s(" %c", &ch);
			}
		}
	}
}